#define _CRT_SECURE_NO_WARNINGS 1

#include "SL.h"

SLN* BuyNewNode(SLDT data)
{
	SLN* newNode = (SLN*)malloc(sizeof(SLN));
	if (newNode == NULL)
	{
		perror("malloc failed");
		return NULL;
	}

	newNode->data = data;
	newNode->next = NULL;

	return newNode;
}

SLN* SLInit()
{
	SLN* head = BuyNewNode(-1);
	if (head == NULL)
	{
		return NULL;
	}

	return head;
}

void SLDestroy(SLN* head)
{
	assert(head);

	SLN* cur = head->next;

	while (cur != NULL)
	{
		SLN* temp = cur;
		cur = cur->next;
		free(temp);
	}

	free(head);
}

void SLInsert(SLN* head, SLDT data)
{
	assert(head);

	SLN* newnode = BuyNewNode(data);
	if (newnode == NULL)
	{
		perror("malloc failed");
		return;
	}

	SLN* cur = head;

	while (cur->next)
	{
		cur = cur->next;
	}

	cur->next = newnode;
}

void SLErase(SLN* head, SLN* node)
{
	assert(head);
	assert(head->next);
	assert(node);

	SLN* cur = head;

	while (cur->next!= node)
	{
		cur = cur->next;
	}

	cur->next = node->next;

	free(node);
}

SLN* SLFind(SLN* head, SLDT data)
{
	assert(head);
	assert(head->next);

	SLN* cur = head->next;

	while (cur)
	{
		if (cur->data == data)
		{
			return cur;
		}

		cur = cur->next;
	}

	return NULL;
}